/**
 * 公用滚动条监听事件
 */

export default {
  data() {
    return {
      _scrollingElement: null,
      _isReachBottom: false,
      leaveHead: false,
      reachTopDistance: 1000,  // 距离顶部多少触发
      reachBottomDistance: 30, // 距离底部多远触发
      scrollBottom: 0
    }
  },
  mounted() {
    window.addEventListener('scroll', this._windowScrollHandler)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this._windowScrollHandler)
  },
  methods: {
    _windowScrollHandler() {
      let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      if (scrollTop > this.reachTopDistance && !this.leaveHead) {
        this.leaveHead = true;
      }
      if (scrollTop < this.reachTopDistance && this.leaveHead) {
        this.leaveHead = false;
      }
      let currentHeight = scrollTop + clientHeight + this.reachBottomDistance;
      if (currentHeight < scrollHeight && this._isReachBottom) {
        this._isReachBottom = false
      }
      if (this._isReachBottom) {
        return
      }
      if (currentHeight >= scrollHeight) {
        this._isReachBottom = true;
        typeof this.reachBottomLoad === 'function' && this.reachBottomLoad()
      }
    }
  },
}